﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace XYZ_Inventory
{
    public partial class RawMaterialOrders : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadGridView();
            }
            tblMakeOrder.Visible = IsPostBack;
        }

        private void LoadGridView()
        {
            XYZDBContext dbContext = new XYZDBContext();
            List<RawMaterialInventory> rawMaterials =
                dbContext.RawMaterialInventories.Where(x => x.Stock <= x.ReorderLevel).ToList();
            GridView1.DataSource = rawMaterials;
            GridView1.DataBind();
        }

        protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (GridView1.SelectedDataKey != null) ddlProduct.SelectedValue = GridView1.SelectedDataKey[0].ToString();
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            XYZDBContext dbContext = new XYZDBContext();
            RawMaterialOrder order = new RawMaterialOrder
            {
                RawMaterialID = Convert.ToInt32(ddlProduct.SelectedValue),
                OrderDate = DateTime.Now,
                Quantity = Convert.ToInt32(txtQty.Text),
                SupplierID = Convert.ToInt32(ddlSupplier.SelectedValue),
                Status = "Pending"
            };

            dbContext.RawMaterialOrders.AddObject(order);
            dbContext.SaveChanges();

            txtQty.Text = "";
            lblStatus.Text = "Raw Material successfully ordered";
            lblStatus.ForeColor = Color.Green;
        }

        protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GridView1.PageIndex = e.NewPageIndex;
            LoadGridView();
        }
    }
}